package com.jasiri.project.lib.sensor

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import com.jasiri.project.lib.dev.util.formatZipString
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.log.HHLog
import org.json.JSONObject

/**
 * 传感器数据：陀螺仪、加速度
 */
object JasiriSensorHelper : SensorEventListener {

    private var sensorManager: SensorManager? = null
    private var accelerometer: Sensor? = null
    private var gyroscope: Sensor? = null
    private var registered = false

    //陀螺仪数据
    var sensorGyroscopeData = ""
    //加速度传感器数据
    var sensorAccelerometerData = ""

    // 初始化-Application
    fun init(context: Context) {
        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
        accelerometer = sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        gyroscope = sensorManager?.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
    }

    /**
     * 注册 - 建议在获取权限之后
     */
    fun register() {
        if (registered) return
        accelerometer?.let {
            sensorManager?.registerListener(this, it, SensorManager.SENSOR_DELAY_UI)
            registered = true
        }
        gyroscope?.let {
            sensorManager?.registerListener(this, it, SensorManager.SENSOR_DELAY_UI)
        }
    }

    /**
     * 注销监听 - 如果是在Application初始化监听，可忽略该方法
     */
    fun unregister() {
        if (!registered) return
        sensorManager?.unregisterListener(this)
        registered = false
    }

    override fun onSensorChanged(event: SensorEvent?) {
        event?.let {
            val x = it.values[0]
            val y = it.values[1]
            val z = it.values[2]
            when (it.sensor.type) {
                Sensor.TYPE_ACCELEROMETER -> {
                    sensorGyroscopeData = "$x,$y,$z"
                }
                Sensor.TYPE_GYROSCOPE -> {
                    sensorAccelerometerData = "$x,$y,$z"
                }
            }
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        // 可忽略
    }

    fun getSubmitDataSensor(path: String,type: String?): String? {
        return try {
            val gyroGzip = JSONObject().apply {
                put("gyro",sensorGyroscopeData)
                put("accler",sensorAccelerometerData)
            }
            HHLog.e(">>>>>>>>>gyroGzip>>>>>>>>>>>$gyroGzip")
            val data = JSONObject().addCommonParams().apply {
                put("path",path)
                put("type",type)
                put("gyroGzip", gyroGzip.toString().formatZipString())
            }
            HHLog.e(">>>>>>>>>sensor data>>>>>>>>>>>$data")
            data.toString()
        } catch (e: Exception) {
            null
        }
    }
}
